package com.testform.java.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by shadow on 2015/11/29.
 *
 */
@Controller
@RequestMapping("/test")
public class FileUploadController {

    @RequestMapping(value = "/fileUpload")
    public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles,
                          HttpServletRequest request, HttpServletResponse response,
                          String birth) throws IOException {
        response.setContentType("text/plain; charset=UTF-8");
        //可以在上传文件的同时接收其它参数
        uname = new String(uname.getBytes("iso-8859-1"),"utf8");
        System.out.println("收到用户[" + uname + "]的文件上传请求");
        //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
        //这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
      /*  String realPath = request.getSession().getServletContext().getRealPath("/upload");*/
        //设置响应给前台内容的数据格式

        //设置响应给前台内容的PrintWriter对象
        PrintWriter out = response.getWriter();
        //上传文件的原名(即上传前的文件名字)
        String originalFilename = null;
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
        //上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
        for (MultipartFile myfile : myfiles) {
            if (myfile.isEmpty()) {
                out.print("1`请选择文件后上传");
                /*out.flush();*/
                return null;
            } else {

                originalFilename = myfile.getOriginalFilename();
                System.out.println(originalFilename);
                //得到tmp的绝对路径
                String tmpPath = request.getServletContext().getRealPath("views") + "\\";
                //System.out.println("根路径" + request.getServletContext().getRealPath("tmp") );
                String resetName = Long.toString(System.currentTimeMillis());
                String testPath = tmpPath + resetName +".jpg";
                myfile.transferTo(new File(testPath));
                System.out.println("文件原名: " + originalFilename);
                System.out.println("文件名称: " + myfile.getName());
                System.out.println("文件长度: " + myfile.getSize());
                System.out.println("文件类型: " + myfile.getContentType());
                System.out.println("========================================");
            }
        }
        out.write("success");

        return null;
    }
}
